<template>
  <div class="stock-manage">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select v-model="searchForm.stockStatus" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in stockStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>库存列表</span>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="handleStockIn">
              <el-icon><Plus /></el-icon>入库
            </el-button>
            <el-button type="warning" @click="handleStockOut">
              <el-icon><Remove /></el-icon>出库
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="商品名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="code" label="商品编码" width="120" />
        <el-table-column prop="type" label="商品类型" width="120" />
        <el-table-column prop="stock" label="当前库存" width="100" align="center" />
        <el-table-column prop="warning" label="警戒值" width="100" align="center" />
        <el-table-column label="库存状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStockStatusType(row)">
              {{ getStockStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdateTime" label="最后更新时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleStockAdjust(row)">调整</el-button>
            <el-button link type="primary" @click="handleStockRecord(row)">记录</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 入库/出库/调整弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="商品名称" v-if="operationType === 'adjust'">
          <el-input v-model="formData.name" disabled />
        </el-form-item>
        <el-form-item label="选择商品" prop="productId" v-else>
          <el-select
            v-model="formData.productId"
            placeholder="请选择商品"
            filterable
          >
            <el-option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number
            v-model="formData.quantity"
            :min="1"
            :precision="0"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 库存记录抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="库存记录"
      size="60%"
      destroy-on-close
    >
      <el-timeline>
        <el-timeline-item
          v-for="(record, index) in stockRecords"
          :key="index"
          :type="record.type === 'in' ? 'success' : record.type === 'out' ? 'danger' : 'warning'"
          :timestamp="record.createTime"
        >
          <h4>{{ getRecordTypeText(record.type) }}</h4>
          <p>数量：{{ record.type === 'out' ? '-' : '+' }}{{ record.quantity }}</p>
          <p>操作人：{{ record.operator }}</p>
          <p>备注：{{ record.remark }}</p>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Search, Refresh, Plus, Remove } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = ref({
  name: '',
  type: '',
  stockStatus: ''
})

// 表格相关
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗相关
const dialogVisible = ref(false)
const operationType = ref<'in' | 'out' | 'adjust'>('in')
const submitting = ref(false)
const formRef = ref<FormInstance>()

const formData = ref({
  productId: '',
  name: '',
  quantity: 1,
  remark: ''
})

const formRules = {
  productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]
}

// 抽屉相关
const drawerVisible = ref(false)
const stockRecords = ref([
  {
    type: 'in',
    quantity: 100,
    operator: '张三',
    createTime: '2023-11-28 10:00:00',
    remark: '首次入库'
  },
  {
    type: 'out',
    quantity: 50,
    operator: '李四',
    createTime: '2023-11-28 11:00:00',
    remark: '订单出库'
  },
  {
    type: 'adjust',
    quantity: 10,
    operator: '王五',
    createTime: '2023-11-28 12:00:00',
    remark: '库存盘点调整'
  }
])

// 选项数据
const typeOptions = [
  { value: '客厅家具', label: '客厅家具' },
  { value: '卧室家具', label: '卧室家具' },
  { value: '餐厅家具', label: '餐厅家具' },
  { value: '书房家具', label: '书房家具' }
]

const stockStatusOptions = [
  { value: 'normal', label: '正常' },
  { value: 'warning', label: '偏低' },
  { value: 'danger', label: '不足' }
]

const productOptions = [
  { value: '1', label: '现代简约沙发' },
  { value: '2', label: '北欧风格书柜' },
  { value: '3', label: '实木餐桌' }
]

// 模拟数据
const tableData = ref([
  {
    id: '1',
    name: '现代简约沙发',
    code: 'SF001',
    type: '客厅家具',
    stock: 50,
    warning: 10,
    lastUpdateTime: '2023-11-28 10:00:00'
  },
  // 更多数据...
])

const dialogTitle = computed(() => {
  const titleMap = {
    in: '商品入库',
    out: '商品出库',
    adjust: '库存调整'
  }
  return titleMap[operationType.value]
})

// 方法
const getStockStatusType = (row: any) => {
  if (row.stock <= row.warning) return 'danger'
  if (row.stock <= row.warning * 2) return 'warning'
  return 'success'
}

const getStockStatusText = (row: any) => {
  if (row.stock <= row.warning) return '库存不足'
  if (row.stock <= row.warning * 2) return '库存偏低'
  return '正常'
}

const getRecordTypeText = (type: string) => {
  const map: Record<string, string> = {
    in: '入库',
    out: '出库',
    adjust: '调整'
  }
  return map[type] || '未知操作'
}

const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const resetSearch = () => {
  searchForm.value = {
    name: '',
    type: '',
    stockStatus: ''
  }
  handleSearch()
}

const loadData = async () => {
  loading.value = true
  try {
    // 这里调用接口获取数据
    total.value = tableData.value.length
  } catch (error) {
    console.error('加载数据失败：', error)
  } finally {
    loading.value = false
  }
}

const handleStockIn = () => {
  operationType.value = 'in'
  dialogVisible.value = true
}

const handleStockOut = () => {
  operationType.value = 'out'
  dialogVisible.value = true
}

const handleStockAdjust = (row: any) => {
  operationType.value = 'adjust'
  dialogVisible.value = true
  formData.value = {
    productId: row.id,
    name: row.name,
    quantity: 1,
    remark: ''
  }
}

const handleStockRecord = (row: any) => {
  drawerVisible.value = true
  // 这里应该根据商品ID获取库存记录
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        ElMessage.success('操作成功')
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('操作失败：', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.stock-manage {
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      
      .el-form-item {
        margin-bottom: 0;
        margin-right: 0;
      }
    }
  }
  
  .list-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

// 响应式处理
@media screen and (max-width: 768px) {
  .stock-manage {
    .search-form {
      .el-form-item {
        width: 100%;
      }
    }
  }
}
</style>